/**
 * @author: 王志昂
 * @create: 2014年6月5日
 * @note: 前端JS公共模块
 * @history:
 * 2014年6月5日 11:39 创建
 */
define(function (require, exports, module) {
    require('jquery');
    require('underscore');
    require("pop")($);
    require("select2")($);
    var ld = require('lib/jquery.loading');
    var Loading = new ld('#loadingBox', '#mask');
    var SuperbUtil = require('SuperbUtil');
    var ItUtil = require('ItUtil');
    var CodeUtil = require('CodeUtil');
    var IssueUtil = {
        weeklyLength: 1,
        issueStatusList: [],
        issueListTpl: require("template/index/issue_list.html"),
        weeklyIssueListTpl: require("template/index/weekly_issue_list.html"),
        requirementIssueListTpl: require("template/index/requirement_issue_list.html"),
        dailyIssueListTpl: require("template/index/daily_issue_list.html"),
        peopleOptionTpl: '<% for (var i in peopleList) { var people = peopleList[i]; if ((typeof occupation != "undefined" && !_.contains(occupation, people.role)) || people.realname == "admin") {continue;} %><option value="<%= people.id %>" <%= _.contains(people_id, people.id) ? "selected" : "" %>><%= (people.nickname ? people.nickname : people.realname) + "--" + people.name %></option><% }; %>',
        issueStatusOptionTpl: '<% for (var i in issueStatusList) { var issueStatus = issueStatusList[i]; %><option value="<%= issueStatus.status %>" <%= status_id == issueStatus.id ? "selected" : "" %>><%= issueStatus.description %></option><% }; %>',
        onlineContentTpl: '<% var count = 1; for (var i in list) { var item = list[i]; %><p><%= count %>、<%= item.name %><br>提出需求人：<%= item.needer_nickname ? item.needer_nickname : item.needer %>&nbsp&nbsp&nbsp&nbsp开发负责人：<%= item.developer_nickname ? item.developer_nickname : item.developer %>&nbsp&nbsp&nbsp&nbsp测试负责人：<%= item.tester_nickname ? item.tester_nickname : item.tester %><br>JIRA地址：<a href="<%= item.jira_url %>" target="_blank"><%= item.jira_url %></a></p><% count++ }%>',
        testContentTpl: '<% var count = 1; for (var i in list) { var item = list[i]; %><p><%= count %>、<%= item.name %><br>提出需求人：<%= item.needer_nickname ? item.needer_nickname : item.needer %>&nbsp&nbsp&nbsp&nbsp开发负责人：<%= item.developer_nickname ? item.developer_nickname : item.developer %>&nbsp&nbsp&nbsp&nbsp测试负责人：<%= item.tester_nickname ? item.tester_nickname : item.tester %><br>JIRA地址：<a href="<%= item.jira_url %>" target="_blank"><%= item.jira_url %></a></p><% count++ }%>',
        developContentTpl: '<% var count = 1; for (var i in list) { var item = list[i]; %><p><%= count %>、<%= item.name %><br>安排：<%= item.developer_nickname ? item.developer_nickname : item.developer %> 完成</p><% count++ }%>',
        selfTestContentTpl: require("template/index/self_test_content.html"),
        criticalTpl: '<option value="1" <%= critical == 1 ? "selected" : "" %>>低</option><option value="2" <%= critical == 2 ? "selected" : "" %>>中</option><option value="3" <%= critical == 3 ? "selected" : "" %>>高</option>',
        issueTypeOptionTpl: '<% for (var i in issueTypeList) { var issueType = issueTypeList[i]; %><option value="<%= issueType.id %>" <%= issue_type == issueType.id ? "selected" : "" %>><%= issueType.name %></option><% }; %>',
        projectOptionTpl: '<% for (var i in projectList) { var projectItem = projectList[i]; %><option value="<%= projectItem.id %>" <%= project == projectItem.id ? "selected" : "" %>><%= projectItem.name %></option><% }; %>',
        branchOptionTpl: require("template/index/branch_list.html"),

        getIssueStatus: function () {
            var self = this;
            $.ajax({
                url: domain + '/home/home/get_issue_status',
                method: 'GET',
                dataType: 'json',
                success: function (data) {
                    self.issueStatusList = data.data;
                    self.renderAddIssueWindowStatusSelect();
                }
            });
        },
        renderAddIssueWindowStatusSelect: function (status_id) {
            status_id = status_id || 0;
            var issueStatusOption = _.template(this.issueStatusOptionTpl, {
                issueStatusList: this.issueStatusList,
                status_id: status_id
            });
            $('#add_issue_window_status').html(issueStatusOption);
        },
        renderAddIssueWindowInput: function (id, name, description, jira_url, status, server_code, possible_effect, self_test_content, self_test_problem, critical) {
            id = id || 0;
            name = name || '';
            description = description || '';
            jira_url = jira_url || '';
            status = status || '';
            server_code = server_code || '', possible_effect = possible_effect || '', self_test_content = self_test_content || '', self_test_problem = self_test_problem || '', $('#add_issue_window_id').val(id);
            $('#add_issue_window_name').val(name);
            $('#add_issue_window_description').val(description);
            $('#add_issue_window_jira_url').val(jira_url);
            $('#add_issue_window_current_table_status').val(status);
            $('#add_issue_window_server_code').val(server_code);
            $('#add_issue_window_possible_effect').val(possible_effect);
            $('#add_issue_window_self_test_content').val(self_test_content);
            $('#add_issue_window_self_test_problem').val(self_test_problem);
            var add_issue_window_critical_html = _.template(this.criticalTpl, {
                critical: critical
            });
            $('#add_issue_window_critical').html(add_issue_window_critical_html);
        },
        renderAddIssueWindowPeopleSelect: function (needer_id, developer_id, tester_id, develop_members) {
            needer_id = needer_id || 0;
            developer_id = developer_id || 0;
            tester_id = tester_id || 0;
            develop_members = develop_members || "";
            var neederOption = _.template(this.peopleOptionTpl, {
                peopleList: peopleList,
                occupation: ['po', 'td', 'pd'],
                people_id: [needer_id],
                _: _
            });
            var developerOption = _.template(this.peopleOptionTpl, {
                peopleList: peopleList,
                occupation: ['dev'],
                people_id: [developer_id],
                _: _
            });
            var developMemberArr = develop_members.split(",");
            var developMembersOption = _.template(this.peopleOptionTpl, {
                peopleList: peopleList,
                occupation: ['dev'],
                people_id: developMemberArr,
                _: _
            });
            var testerOption = _.template(this.peopleOptionTpl, {
                peopleList: peopleList,
                occupation: ['qa'],
                people_id: [tester_id],
                _: _
            });
            $('#add_issue_window_needer').html(neederOption).select2();
            $('#add_issue_window_developer').html(developerOption).select2();
            $('#add_issue_window_develop_members').html(developMembersOption).select2();
            $('#add_issue_window_tester').html(testerOption).select2();
        },
        renderAddIssueWindowIssueTypeSelect: function (issue_type) {
            issue_type = issue_type || 1;
            var issueTypeOptionHtml = _.template(this.issueTypeOptionTpl, {
                issueTypeList: issueTypeList,
                issue_type: issue_type
            });
            $('#add_issue_window_type').html(issueTypeOptionHtml);
        },
        renderAddIssueWindowProjectSelect: function (project) {
            project = project || 0;
            var projectOptionHtml = _.template(this.projectOptionTpl, {
                projectList: projectList,
                project: project
            });
            $('#add_issue_window_project').html(projectOptionHtml).select2();
        },
        renderAddIssueWindowBranchSelect: function (branch, branch_type, branch_project) {
            branch = branch || 0;
            branch_type = branch_type || "";
            branch_project = branch_project || "";
            var branchOptionHtml = _.template(this.branchOptionTpl, {
                branchList: branchList,
                branch: branch
            });
            $('#add_issue_window_branch').html(branchOptionHtml).select2();
        },
        renderOnDutyPeople: function (onDutyList) {
            var onDutyStr = "";
            for (var i in onDutyList) {
                var onDuty = onDutyList[i];
                onDutyStr += " " + onDuty.name;
            }
            $('#who-is-on-duty').text(onDutyStr);
        },
        renderSearchPeopleSelect: function (needer_id, developer_id, tester_id) {
            developer_id = developer_id || 0;
            var developerOption = _.template(this.peopleOptionTpl, {
                peopleList: peopleList,
                occupation: ['dev'],
                people_id: developer_id,
                _: _
            });
            $('#search_developer').html(developerOption).select2();
        },
        renderSearchDailyReportPeopleSelect: function (needer_id, developer_id, tester_id) {
            developer_id = developer_id || 0;
            var developerOption = _.template(this.peopleOptionTpl, {
                peopleList: peopleList,
                occupation: ['dev', 'po', 'qa'],
                people_id: developer_id,
                _: _
            });
            $('#search_people').html(developerOption).select2();
        },
        renderAddIssueWindowDeviceType: function (device_type) {
            device_type = device_type || "";
            var deviceTypeArr = device_type.split(",");
            $('input[name="device_type"]').each(function () {
                if (_.contains(deviceTypeArr, $(this).val())) {
                    $(this).prop("checked", true);
                    $(this).parent().addClass("checked");
                }
            });
        },
        renderWishTimePicker: function (wish_time, wish_origin_time) {
            $('#add_issue_window_wish_time').val(wish_time);
            $('#add_issue_window_wish_origin_time').val(wish_origin_time);
        },
        getIssueType: function () {
            var self = this;
            $.ajax({
                url: domain + '/home/home/get_issue_type',
                method: 'GET',
                dataType: 'json',
                success: function (data) {
                    issueTypeList = data.data;
                    self.renderAddIssueWindowIssueTypeSelect();
                }
            });
        },
        getPeople: function (type) {
            var self = this;
            $.ajax({
                url: domain + '/home/home/get_people',
                method: 'GET',
                dataType: 'json',
                success: function (data) {
                    // @todo 这里的简单工厂模式不好，因为issue_util和it和code造成了强耦合关系，如果加个页面就得改代码，最好提取出来放到superb_util.js里面，传入util对象，所有的util实现renderPeople(peopleList)方法，需要重构issue_util.js。
                    peopleList = data.data;
                    if (typeof type == "undefined") {
                        self.renderAddIssueWindowPeopleSelect();
                    } else if (type == 'search') {
                        self.renderSearchPeopleSelect();
                        self.renderSearchDailyReportPeopleSelect();
                    } else if (type == 'ecs') {
                        ItUtil.renderAddEcsWindowPeopleSelect(peopleList);
                    } else if (type == 'code') {
                        CodeUtil.renderAddSubscribeWindowPeopleSelect(peopleList);
                    }
                }
            });
        },
        getProject: function () {
            var self = this;
            $.ajax({
                url: domain + '/home/home/get_project',
                method: 'GET',
                dataType: 'json',
                success: function (data) {
                    projectList = data.data;
                    self.renderAddIssueWindowProjectSelect();
                }
            });
        },
        getBranch: function () {
            var self = this;
            $.ajax({
                url: domain + '/home/home/get_branch',
                method: 'GET',
                dataType: 'json',
                success: function (data) {
                    branchList = data.data;
                    self.renderAddIssueWindowBranchSelect();
                }
            });
        },
        getOnDuty: function () {
            var self = this;
            $.ajax({
                url: domain + '/home/home/get_on_duty',
                method: 'GET',
                dataType: 'json',
                success: function (data) {
                    onDutyList = data.data;
                    self.renderOnDutyPeople(onDutyList);
                }
            });
        },
        getIssue: function (searchCondition, callback) {
            var id = searchCondition.id || 0;
            var date = searchCondition.date || null;
            var status = searchCondition.status || 0;
            var developer = searchCondition.developer || null;
            var people = searchCondition.people || null;
            var page = searchCondition.page || null;
            $.ajax({
                url: domain + '/home/home/get_issue',
                method: 'GET',
                data: {
                    id: id,
                    status: status,
                    date: date,
                    report_type: searchCondition.reportType,
                    developer: developer,
                    people: people,
                    page: page
                },
                dataType: 'json',
                success: function (data) {
                    callback(data);
                }
            });
        },
        initIssueList: function (issueListCondition) {
            var self = this;
            var status, isWeekly, tableSelector, tpl, date, developer, people, page;
            if (issueListCondition) {
                status = issueListCondition.status || 0;
                isWeekly = issueListCondition.isWeekly || 0;
                tableSelector = issueListCondition.tableSelector || '#issue_list';
                tpl = issueListCondition.tpl || self.issueListTpl;
                date = issueListCondition.date || null;
                developer = issueListCondition.developer || '';
                people = issueListCondition.people || '';
                page = issueListCondition.page || null;
            } else {
                status = 0;
                isWeekly = 0;
                tableSelector = '#issue_list';
                tpl = self.issueListTpl;
                date = null;
                developer = '';
                people = '';
                page = null;
            }

            Loading.show();
            var searchIssueCondition = {
                id: 0,
                status: status,
                date: date,
                reportType: isWeekly,
                developer: developer,
                people: people,
                page: page
            };
            self.getIssue(searchIssueCondition, function (data) {
                var issueListHtml = _.template(tpl, {
                    list: data.data.content,
                    timeFormat: SuperbUtil.timeFormat
                });
                $(tableSelector).html(issueListHtml);
                SuperbUtil.moreData(data, page, searchIssueCondition, self);
                Loading.hide();
            });
        },
        initWeeklyReportIssue: function () {
            var self = this;
            Loading.show();
            var searchIssueCondition = {
                id: 0,
                status: [4, 5, 6, 7],
                date: date,
                reportType: 1
            };
            self.getIssue(searchIssueCondition, function (data) {
                var tpl = self.weeklyIssueListTpl;
                var issueListHtml = _.template(tpl, {
                    list: data.data.content,
                    count: self.weeklyLength,
                    timeFormat: SuperbUtil.timeFormat
                });
                if (!!data.data.content) {
                    self.weeklyLength += _.size(data.data.content);
                }
                $('#this-week-work').html(issueListHtml);
                Loading.hide();
            });

            searchIssueCondition = {
                id: 0,
                status: [3, 4, 5],
                date: date,
                reportType: 1
            };
            self.getIssue(searchIssueCondition, function (data) {
                var tpl = self.weeklyIssueListTpl;
                var issueListHtml = _.template(tpl, {
                    list: data.data.content,
                    count: self.weeklyLength,
                    timeFormat: SuperbUtil.timeFormat
                });
                if (!!data.data.content) {
                    self.weeklyLength += _.size(data.data.content);
                }
                $('#next-week-work').html(issueListHtml);
                Loading.hide();
            });
        },
        initMonthlyReportIssue: function () {
            Loading.show();

            var searchIssueCondition = {
                id: 0,
                status: 7,
                date: date,
                reportType: 2
            };
            this.getIssue(searchIssueCondition, function (data) {
                var tpl = '<% var count = 1; for (var i in list) { var item = list[i]; %><p><%= count %>、<%= item.name %>-<%= item.developer %> 上线</p><% count++ } %>';
                var issueListHtml = _.template(tpl, {
                    list: data.data.content
                });
                $('#this-month-work-online').html(issueListHtml);
                Loading.hide();
            });

            searchIssueCondition = {
                id: 0,
                status: 6,
                date: date,
                reportType: 2
            };
            this.getIssue(searchIssueCondition, function (data) {
                var tpl = '<% var count = 1; for (var i in list) { var item = list[i]; %><p><%= count %>、<%= item.name %> 完成</p><% count++ } %>';
                var issueListHtml = _.template(tpl, {
                    list: data.data.content
                });
                $('#this-month-work-finish').html(issueListHtml);
                Loading.hide();
            });

            searchIssueCondition = {
                id: 0,
                status: 5,
                date: date,
                reportType: 2
            };
            this.getIssue(searchIssueCondition, function (data) {
                var tpl = '<% var count = 1; for (var i in list) { var item = list[i]; %><p><%= count %>、<%= item.name %> 完成</p><% count++ } %>';
                var issueListHtml = _.template(tpl, {
                    list: data.data.content
                });
                $('#this-month-work-test').html(issueListHtml);
                Loading.hide();
            });
        },
        bindAddIssueButtonEvent: function () {
            $('#addBtn').click(function () {
                $('#add_issue_window').popup({
                    filter: '#mask',
                    zindex: 9990
                });
            });
        },
        bindAddIssueWindowCloseEvent: function () {
            var self = this;
            $('#add_issue_window').find('.remove').click(function () {
                self.renderAddIssueWindowInput();
                self.renderAddIssueWindowIssueTypeSelect();
                self.renderAddIssueWindowProjectSelect();
                self.renderAddIssueWindowBranchSelect();
                self.renderAddIssueWindowPeopleSelect();
                self.renderAddIssueWindowStatusSelect();
                $('#add_issue_window').pophide({
                    filter: '#mask'
                });
            });
            $('#add_issue_window_cancel_btn').click(function () {
                self.renderAddIssueWindowInput();
                self.renderAddIssueWindowIssueTypeSelect();
                self.renderAddIssueWindowProjectSelect();
                self.renderAddIssueWindowBranchSelect();
                self.renderAddIssueWindowPeopleSelect();
                self.renderAddIssueWindowStatusSelect();
                $('#add_issue_window').pophide({
                    filter: '#mask'
                });
            });
        },
        bindSaveIssueButtonEvent: function (callback) {
            $('#add_issue_window_save_btn').click(function () {
                var id = $('#add_issue_window_id').val();
                var name = $('#add_issue_window_name').val();
                var description = $('#add_issue_window_description').val();
                var needer = $('#add_issue_window_needer').val();
                var developer = $('#add_issue_window_developer').val();
                var develop_members = $('#add_issue_window_develop_members').val();
                var tester = $('#add_issue_window_tester').val();
                var jira_url = $('#add_issue_window_jira_url').val();
                var status = $('#add_issue_window_status').val();
                var critical = $('#add_issue_window_critical').val();
                var server_code = $('#add_issue_window_server_code').val();
                var possible_effect = $('#add_issue_window_possible_effect').val();
                var self_test_content = $('#add_issue_window_self_test_content').val();
                var self_test_problem = $('#add_issue_window_self_test_problem').val();
                var branch = $('#add_issue_window_branch').val();
                var project = $('#add_issue_window_project').val();
                var issue_type = $('#add_issue_window_type').val();
                var wish_origin_time = $('#add_issue_window_wish_origin_time').val();
                var wish_time = $('#add_issue_window_wish_time').val();
                var device_type = [];
                $('input[name="device_type"]:checked').each(function () {
                    device_type.push($(this).val());
                });
                $.ajax({
                    url: domain + '/home/home/save_issue',
                    method: 'GET',
                    dataType: 'json',
                    data: {
                        id: id,
                        name: name,
                        description: description,
                        needer: needer,
                        developer: developer,
                        develop_members: develop_members,
                        tester: tester,
                        jira_url: jira_url,
                        status: status,
                        critical: critical,
                        server_code: server_code,
                        possible_effect: possible_effect,
                        self_test_content: self_test_content,
                        self_test_problem: self_test_problem,
                        branch: branch,
                        project: project,
                        issue_type: issue_type,
                        wish_origin_time: wish_origin_time,
                        wish_time: wish_time,
                        device_type: device_type
                    },
                    success: function (data) {
                        alert(data.errorMsg);
                        if (data.errorCode == 0) {
                            $('#add_issue_window').find('.remove').click();
                            callback();
                        }
                    }
                });
            });
        },
        bindIssueEditButtonEvent: function () {
            var self = this;
            $(document).on('click', '.editBtn', function () {
                var id = $(this).parents('tr').find('.issue_id').text();
                var searchIssueCondition = {
                    id: id,
                    status: 0,
                    date: null,
                    reportType: 0
                };
                self.getIssue(searchIssueCondition, function (data) {
                    var res = _.toArray(data.data.content);
                    var item = _.first(res);
                    self.renderAddIssueWindowInput(item.id, item.name, item.description, item.jira_url, item.status_id, item.server_code, item.possible_effect, item.self_test_content, item.self_test_problem, item.critical);
                    self.renderAddIssueWindowPeopleSelect(item.needer_id, item.developer_id, item.tester_id, item.develop_members);
                    self.renderAddIssueWindowIssueTypeSelect(item.issue_type);
                    self.renderAddIssueWindowProjectSelect(item.project);
                    self.renderAddIssueWindowBranchSelect(item.branch, item.branch_type, item.branch_project);
                    self.renderAddIssueWindowStatusSelect(item.status_id);
                    self.renderAddIssueWindowDeviceType(item.device_type);
                    self.renderWishTimePicker(item.wish_time, item.wish_origin_time);
                    $('#add_issue_window').popup({
                        filter: '#mask',
                        zindex: 9990
                    });
                });
            });
        },
        bindIssueDeleteButtonEvent: function () {
            var self = this;
            $(document).on('click', '.deleteBtn', function () {
                if (!confirm('确定要删除该需求？')) {
                    return false;
                }
                var id = $(this).parents('tr').find('.issue_id').text();
                $.ajax({
                    url: domain + '/home/home/delete_issue',
                    method: 'GET',
                    data: {
                        id: id
                    },
                    dataType: 'json',
                    success: function (data) {
                        alert(data.errorMsg);
                        location.reload();
                    }
                });
            });
        },
        bindSelfTestSearchBtn: function (issueListCondition) {
            var self = this;
            $(document).on('click', '#searchBtn', function () {
                issueListCondition.developer = $('#search_developer').val();
                self.initIssueList(issueListCondition);
            });
        },
        bindDailyReportSearchBtn: function (issueListCondition) {
            var self = this;
            $(document).on('click', '#searchBtn', function () {
                var people = $('#search_people').val();
                self.initEveryDayIssue(people);
            });
        },
        initEveryDayIssue: function (people) {
            var self = this;
            people = people || "";
            var issueListCondition = {
                status: [4, 5, 6, 7],
                date: date,
                isWeekly: 0,
                people: people,
                tableSelector: '#today-work',
                tpl: self.dailyIssueListTpl
            };
            self.initIssueList(issueListCondition);

            issueListCondition = {
                status: [3, 4, 5, 6],
                date: date,
                isWeekly: 0,
                people: people,
                tableSelector: '#tomorrow-work',
                tpl: self.dailyIssueListTpl
            };
            self.initIssueList(issueListCondition);

        },
        bindPageEvent: function (issueListCondition, page) {
            var self = this;
            var status = issueListCondition.status || 0;
            var isWeekly = issueListCondition.isWeekly || 0;
            var tableSelector = issueListCondition.tableSelector || '#issue_list';
            var tpl = issueListCondition.tpl || self.issueListTpl;
            var date = issueListCondition.date || null;
            var developer = issueListCondition.developer || '';
            issueListCondition.page = page;
            self.initIssueList(issueListCondition);
        }
    };
    module.exports = IssueUtil;
});
